<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家名称" prop="merName">
        <el-input
            v-model="queryParams.merName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺类型" prop="bizType">
        <el-select v-model="queryParams.bizType" placeholder="请选择店铺类型" clearable>
          <el-option
              v-for="dict in shop_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in t_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              v-show="dict.value !== '10' && dict.value !== '11' && dict.value !== '12'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="cityCode">
        <el-cascader-area v-model="queryParams.cityCode" :qrtType="1"></el-cascader-area>
      </el-form-item>
      <el-form-item label="经销商" prop="parName">
        <el-input
            v-model="queryParams.parName"
            placeholder="请输入经销商"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tshop:add']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tshop:remove']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tshop:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tshopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商家名称" align="center" prop="merName">
        <template #default="scope">
          <span style="color:red;" v-if="scope.row.merStatus =='04'">{{ scope.row.merName }}</span>
          <span v-else>{{ scope.row.merName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="shopName"/>
      <el-table-column label="店铺类型" align="center" prop="bizType">
        <template #default="scope">
          <dict-tag :options="shop_type" :value="scope.row.bizType"/>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" width="200" align="center" prop="addrDesc"/>
      <el-table-column label="客服电话" align="center" prop="serviceTel"/>
      <el-table-column label="营业额" align="center" prop="amount"/>
      <el-table-column label="实际营收" align="center" prop="merAmount"/>
      <el-table-column label="平台佣金" align="center" prop="platAmount"/>
      <el-table-column label="经销商佣金" align="center" prop="parAmount"/>
      <el-table-column label="经销商" align="center" prop="parName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="t_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="审核原因" align="center" prop="statusReason"/>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:tshop:query']">查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && scope.row.status !== '04'))}"
                     v-hasPermi="['system:tshop:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && (scope.row.status === '00' || scope.row.status === '03')))}"
                     v-hasPermi="['system:tshop:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Select" @click="handleSubmitAudit(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && (scope.row.status === '00' || scope.row.status === '03')))}"
                     v-hasPermi="['system:tshop:submit']">提交
          </el-button>
          <el-button link type="primary" icon="DocumentDelete" @click="handleCancelSubmit(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && scope.row.status === '01'))}"
                     v-hasPermi="['system:tshop:cancel']">撤回
          </el-button>
          <el-button link type="primary" icon="CloseBold" @click="handleTerminate(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.status === '02'))}"
                     v-hasPermi="['system:tshop:terminate']">终止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改店铺列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="tshopRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="merId" v-if="disableNum===0">
              <mer-select :key="refreshTime" v-model="form.merId" :typeList=[1,2]
                          :disabledValue="disableNum"></mer-select>
            </el-form-item>
            <el-form-item label="商家名称" v-if="disableNum===1">
              {{ form.merName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="shopName">
              <el-input v-model="form.shopName" placeholder="请输入店铺名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺类型" prop="bizType">
              <el-select v-model="form.bizType" placeholder="请选择店铺类型">
                <el-option
                    v-for="dict in shop_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业时间" prop="bizHours">
              <el-input v-model="form.bizHours" placeholder="请输入营业时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="blisNo">
              <el-input v-model="form.blisNo" placeholder="请输入营业执照号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="blisPic">
              <image-upload v-model="form.blisPic" :limit="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客服电话" prop="serviceTel">
              <el-input v-model="form.serviceTel" placeholder="请输入客服电话" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="areaCode">
              <el-cascader-area v-model="form.areaCode" :qrtType="2"></el-cascader-area>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="addr">
              <el-input v-model="form.addr" type="textarea" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <map-component :key="mapComponentKey"
                           :longitude="form.longitude" :latitude="form.latitude"
                           @coordinateClicked="handleCoordinateClicked"
            ></map-component>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="shopMainPic">
              <image-upload v-model="form.shopMainPic" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="shopDetailPic">
              <image-upload v-model="form.shopDetailPic" :limit="9"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="shopDesc">
              <editor v-model="form.shopDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveForm">保 存</el-button>
          <el-button @click="submitForm">提 交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 查看商家详情 -->
     <el-dialog title="商家详情" v-model="viewOpen" width="1000px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          
          <el-col :span="12">
            <el-form-item label="商家名称" prop="merId">
              <!--              <mer-select :key="refreshTime" v-model="form.merId" :typeList=[1,2]-->
              <!--                          :disabledValue="1"></mer-select>-->
              {{ form.merName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="shopName">
              <!-- <el-input v-model="form.shopName" placeholder="请输入店铺名称" :disabled="true"/> -->
              {{ form.shopName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺类型" prop="bizType">
              <el-select v-model="form.bizType" placeholder="请选择店铺类型" :disabled="true">
                <el-option
                    v-for="dict in shop_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业时间" prop="bizHours">
              <!-- <el-input v-model="form.bizHours" placeholder="请输入营业时间" :disabled="true"/> -->
              {{ form.bizHours }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="blisNo">
              <el-input v-model="form.blisNo" placeholder="请输入营业执照" type="number" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照图片" prop="blisPic">
              <image-preview :src="form.blisPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="客服电话" prop="serviceTel">
              <el-input v-model="form.serviceTel" placeholder="请输入客服电话" type="number" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="addrDesc" label-width="auto">
              {{ form.addrDesc }}
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="shopMainPic">
              <image-preview :src="form.shopMainPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
           
            <el-form-item label="详情图" prop="shopDetailPic">
              <image-preview :src-list="form.shopDetailPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="shopDesc">
              <editor v-model="form.shopDesc" :min-height="192" :readOnly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
       
        
        
        
       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Tshop">
import {listTshop, getTshop, delTshop, addTshop, updateTshop, updateStatus} from "@/api/system/tshop";
import router from "@/router";
import {watch, onBeforeUnmount, ref} from "vue";
import useUserStore from "@/store/modules/user";
import MerSelect from "@/components/MerSelect/index.vue";
import {getAreaCode} from "@/api/system/sysCity";

const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {shop_type, t_status} = proxy.useDict('shop_type', 't_status');

const tshopList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const disableNum = ref(0);
const mapComponentKey = ref(0);
const refreshTime = ref(0); //组件刷新次数
const viewOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merId: undefined,
    shopName: undefined,
    shopDesc: undefined,
    type: 1,
    bizHours: undefined,
    bizType: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: undefined,
    latitude: undefined,
    serviceTel: undefined,
    status: undefined,
    statusReason: undefined
  },
  rules: {
    merId: [
      {required: true, message: "商家名称不能为空", trigger: "blur"}
    ],
    shopName: [
      {required: true, message: "店铺名称不能为空", trigger: "blur"}
    ],
    bizType: [
      {required: true, message: "店铺类型不能为空", trigger: "blur"}
    ],
    bizHours: [
      {required: true, message: "营业时间不能为空！", trigger: "change"},
    ],
    areaCode: [
      {required: true, message: "地区不能为空！", trigger: "change"},
    ],
    addr: [
      {required: true, message: "详细地址不能为空！", trigger: "change"},
    ],
    shopMainPic: [
      {required: true, message: "主图不能为空", trigger: "blur"}
    ],
    shopDetailPic: [
      {required: true, message: "详情图不能为空", trigger: "blur"}
    ],
    serviceTel: [
      {required: true, message: "客服电话不能为空", trigger: "blur"}
    ],
    shopDesc: [
      {required: true, message: "店铺描述不能为空", trigger: "blur"}
      , {validator: validateEditor, message: "店铺描述不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

function validateEditor(rule, value, callback) {
  if (value === null || value === undefined || value === '<p></p>' || value === '<p><br></p>') {
    callback(new Error('不能为空'));
  } else {
    callback();
  }
}
/** 查询店铺列表列表 */
function getList() {
  loading.value = true;
  listTshop(queryParams.value).then(response => {
    tshopList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    shopId: undefined,
    merId: undefined,
    merName: undefined,
    shopName: undefined,
    shopMainPic: undefined,
    shopDetailPic: undefined,
    shopDesc: undefined,
    type: 1,
    bizHours: undefined,
    bizType: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: 118.8083,
    latitude: 31.8639,
    serviceTel: undefined,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  mapComponentKey.value += 1;
  proxy.resetForm("tshopRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // ids.value = selection.map(item => item.shopId);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;

  ids.value = selection.map(item => item.shopId);
  single.value = selection.length != 1;
  // multiple.value = !selection.length;
  let type = true
  if(selection.length == 1) {
    // 只选择一个
   
    if(selection[0].merStatus === '02' && (selection[0].status === '00' || selection[0].status === '03')) {
      type = false
    } else {
      type = true
    }
  }else {
    // 选择多个
    type = false
    if(selection.length == 0) {
      type = true
    }else {
      selection.map(item => {
        if(item.status !== '00' && item.status !== '03') {
          type = true
          return
        }
      })
    }
    
  }
  multiple.value = type
}

/** 新增按钮操作 */
function handleAdd() {
  disableNum.value = 0
  refreshTime.value += 1
  reset();
  open.value = true;
  title.value = "添加店铺";
  mapComponentKey.value += 1;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disableNum.value = 1
  reset();
  const _shopId = row.shopId || ids.value
  getTshop(_shopId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改店铺";
    refreshTime.value += 1
    mapComponentKey.value += 1;
  });


}

/** 提交按钮 */
function saveForm() {
  if(form.value.shopDesc) {
    form.value.shopDesc = form.value.shopDesc.replace(/<img/g, '<img style="max-width: 100%;height: auto;"');
    form.value.shopDesc = form.value.shopDesc.replace('<iframe', `<video controls="" autoplay="" style="width: 100%;"`).replace('</iframe>', '</video>')
  }
  proxy.$refs["tshopRef"].validate(valid => {
    if (valid) {
      if (form.value.shopId != null) {
        updateTshop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTshop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function submitForm() {
  proxy.$refs["tshopRef"].validate(valid => {
    if (valid) {
      form.value.status = '01';
      if (form.value.shopId != null) {
        updateTshop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTshop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shopIds = row.shopId || ids.value;
  proxy.$modal.confirm('是否确认删除店铺编号为"' + _shopIds + '"的数据项？').then(function () {
    return delTshop(_shopIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleSubmitAudit(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认提交店铺审核，编号为"' + _merIds + '"的数据项？').then(function () {
    row.status = "01";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("提交成功");
  }).catch(() => {
  });
}

function handleCancelSubmit(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认撤回店铺审核，编号为"' + _merIds + '"的数据项？').then(function () {
    row.status = "00";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("撤回成功");
  }).catch(() => {
  });
}

function handleTerminate(row) {
  const _merIds = row.merId || ids.value;
  proxy.$modal.confirm('是否确认终止店铺，编号为"' + _merIds + '"的数据项？').then(function () {
    row.status = "04";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("终止成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tshop/export', {
    ...queryParams.value
  }, `tshop_${new Date().getTime()}.xlsx`)
}

function handleCoordinateClicked(coordinate) {
  // 更新经纬度
  form.value.longitude = coordinate.lng;
  form.value.latitude = coordinate.lat;
  form.value.addr = coordinate.addr;
  getAreaCode({
    provinceExtName: coordinate.province,
    cityExtName: coordinate.city,
    districtExtName: coordinate.district,
    isOpenCity: 0
  }).then(response => {
    form.value.areaCode = response.data.district;
  });
}

onActivated(() => {
  getList();
})

/** 详细按钮操作 */
function handleView(row) {
  const _shopId = row.shopId || ids.value
  getTshop(_shopId).then(response => {
    refreshTime.value += 1
    response.data.shopDetailPic = response.data.shopDetailPic.split(',')
    form.value = response.data;
    viewOpen.value = true;
   
  });
}

getList();
// const stopWatching = watch(() => useUserStore().cascaderKey, (v) => {
//   getList();
// }, {immediate: true});
// onBeforeUnmount(() => {
//   stopWatching();
// });
</script>
